<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use App\Supports\Sms\Sms;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use App\Services\UpdateUserInfo\UpdateUserInfo;
use App\Services\RegisterNewUser\RegisterNewUser;
use App\Services\SearchTeamMember\SearchTeamMember;
use App\Services\GoldStormSupport\GoldStormSupport;
use App\Services\UpdateUserInfo\UpdateUserInfoRequest;
use App\Services\UpdateUserInfo\BindUserPayMethodRequest;
use App\Services\UserFromInviteCode\UserFromInviteCode;
use App\Http\Controllers\Api\V1\Resources\UserResource;
use App\Http\Controllers\Api\V1\Resources\UserTeamResource;
use App\Services\RegisterNewUser\RegisterNewUserRequest;
use App\Services\AuthUser\AuthUserRequest;
use App\Services\AuthUser\AuthUser;
use App\Services\UserCall\UserCall;
use App\Models\RegisterPhone;
use App\Services\GoldStormSupport\GoldStormSupportRequest;
use App\Services\SearchTeamMember\SearchTeamMemberRequest;
use App\Http\Controllers\Api\V1\Requests\UserUpdateRequest;
use App\Services\UserFromInviteCode\UserFromInviteCodeRequest;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;


class UsersController extends Controller
{
	public function store()
	{
		$lock = Cache::lock('register_new_user', 15);
		
		try {

			if (! $lock->get()) return fail('请重试');

			$request = app(RegisterNewUserRequest::class);

			$user = app(RegisterNewUser::class, [
				'name' => $request->name,
				'phone' => $request->phone,
				'password' => $request->password,
				'inviteCode' => $request->invite_code
			])->register();

		
			app(Sms::class)->cleanCachedDataAfterUsing(request('sms_key'));

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}

    public function show(): JsonResponse
    {
	    /**
	     * @var User $user
	     */
    	$user = request()->user();
    	return response()->json($user->getCache());
    }

    public function payMethod(): JsonResponse
    {
	    /**
	     * @var User $user
	     */
    	$user = User::find(request()->user_id);
    	return response()->json($user->getCachePay());
    }

    public function userChildInfo()
    {
	    /**
	     * @var User $user
	     */
    	$child = User::where("phone",request()->phone)->first();
    	$user = request()->user();
    	if(!$child){
    		fail('用户不存在!');
    	}elseif($child->id <= $user->id){
    		fail('当前用户不是您的下级');
    	}elseif(!$user->djUser($child)){
    		fail('当前用户不是您的下级');

    	}

    	return response()->json(['child_name'=>$child->name,"child_id"=>$child->id]);
    }

    public function call()
    {
	    /**
	     * @var User $user
	     */

    	if(!request()->call_phone){
    		fail('联系电话不存在！');

    	}
		$result =  app(UserCall::class, [
		    'callPhone' => request()->call_phone,
	    ])->call();

    	return response()->json($result);
    }


    public function fromInviteCode(UserFromInviteCodeRequest $request): UserResource
    {
    	$user = app(UserFromInviteCode::class, ['inviteCode' => $request->invite_code])->get();
	    return new UserResource($user);
    }

    public function team(): AnonymousResourceCollection
    {
	    /**
	     * @var User $user
	     */
	    $user = request()->user();
	    return UserTeamResource::collection($user->myTeamMembers());
    }


    public function agents()
    {
	    /**
	     * @var User $user
	     */
	    $agents = User::query()->where('is_agent',true)->orderBy('id')->paginate();
	    return UserResource::collection($agents);
    }

    public function search(SearchTeamMemberRequest $request): AnonymousResourceCollection
    {
    	$members = app(SearchTeamMember::class, [
    		'user' => $request->user(),
    		'scope' => $request->scope,
		    'keyword' => $request->keyword
	    ])->search();

	    return UserResource::collection($members);
    }

    public function todayBonusRank(): JsonResponse
    {
	    /**
	     * @var User $user
	     */
    	$user = request()->user();
    	$index = (int)request('index', 0);
	    return response()->json($user->dayBonusRank($index));
    }

    public function allBonusRank(): JsonResponse
    {
	    /**
	     * @var User $user
	     */
	    $user = request()->user();
	    $index = (int)request('index', 0);
	    return response()->json($user->allBonusRank($index));
    }



	 public function bindUserPayMethod()
    {
	    $lock = Cache::lock('bind_user_pay_method', 15);

	    try {

	    	if (! $lock->get()) fail('请重试');

	    	$request = app(BindUserPayMethodRequest::class);

		    app(UpdateUserInfo::class, [
			    'request' => $request,
		    ])->update();

            return response(null, 204);

	    } finally {
		    $lock->release();
	    }
    }


    public function update()
    {
	    $lock = Cache::lock('update_user_info', 1);

	    try {

	    	if (! $lock->get()) fail('请重试');

	    	$request = app(UpdateUserInfoRequest::class);

		    app(UpdateUserInfo::class, [
			    'request' => $request,
		    ])->update();

            return response(null, 204);

	    } finally {
		    $lock->release();
	    }
    }

    public function setChildNickname(User $user)
    {
        /**
         * @var User $user
         */
        $res = request()->user();
    	$res->setChildNickname($user);
	    return response(null, 204);
    }

	public function support()
	{
		$lock = Cache::lock('beans_support', 15);

		try {

			if (! $lock->get()) fail('处理中...请勿频繁操作');

			$request = app(GoldStormSupportRequest::class);

			/**
			 * @var User $user
			 */
			$user = $request->user();

			need_paycode($user);

			app(GoldStormSupport::class, [
                'child' => $request->getChild()
            ])->support();

			$user->resetPayCodeTry();

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}


	public function authUser()
	{
		$lock = Cache::lock('auth_user', 1);

		try {

			if (! $lock->get()) return fail('请重试');

			$request = app(AuthUserRequest::class);
			

			app(AuthUser::class, [
				'realName' => $request->real_name,
				'identifyNum' => $request->identify_num,
			])->auth();

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}
}
